<template>
  <div class="wechat-users">
    <el-card>
      <div slot="header" class="header">
        <span>微信用户管理</span>
        <el-button type="primary" @click="showSendMessage = true">发送消息</el-button>
      </div>
      
      <div class="filters">
        <el-input v-model="filters.keyword" placeholder="搜索昵称或OpenID" style="width: 200px;" />
        <el-select v-model="filters.subscribe_status" placeholder="关注状态" style="width: 120px;">
          <el-option label="已关注" :value="1" />
          <el-option label="未关注" :value="0" />
        </el-select>
        <el-button type="primary" @click="fetchUsers">搜索</el-button>
      </div>

      <el-table :data="users" v-loading="loading">
        <el-table-column prop="nickname" label="昵称" />
        <el-table-column prop="user_open_id" label="OpenID" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{ scope.row.user_open_id }}</span>
            <el-button 
              type="text" 
              size="mini" 
              @click="copyOpenId(scope.row.user_open_id)"
              style="margin-left: 5px;"
            >
              <i class="el-icon-copy-document"></i>
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="subscribe_status" label="关注状态">
          <template slot-scope="scope">
            <el-tag :type="scope.row.subscribe_status === 1 ? 'success' : 'danger'">
              {{ scope.row.subscribe_status === 1 ? '已关注' : '未关注' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="subscribe_time" label="关注时间" />
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="small" @click="sendToUser(scope.row)">发送消息</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :current-page="pagination.page"
        :page-size="pagination.limit"
        :total="pagination.total"
        @current-change="handlePageChange"
      />
    </el-card>

    <!-- 发送消息弹窗 -->
    <el-dialog title="发送消息" :visible.sync="showSendMessage" width="500px">
      <el-form :model="messageForm" label-width="80px">
        <el-form-item label="发送类型">
          <el-radio-group v-model="messageForm.type">
            <el-radio label="single">单个用户</el-radio>
            <el-radio label="all">全部用户</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="messageForm.type === 'single'" label="用户">
          <el-input v-model="messageForm.user_open_id" placeholder="用户OpenID" />
        </el-form-item>
        <el-form-item label="消息内容">
          <el-input v-model="messageForm.content" type="textarea" :rows="4" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="showSendMessage = false">取消</el-button>
        <el-button type="primary" @click="sendMessage" :loading="sending">发送</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'WechatUsers',
  data() {
    return {
      users: [],
      loading: false,
      showSendMessage: false,
      sending: false,
      filters: {
        keyword: '',
        subscribe_status: 1
      },
      pagination: {
        page: 1,
        limit: 20,
        total: 0
      },
      messageForm: {
        type: 'single',
        user_open_id: '',
        content: ''
      }
    }
  },
  mounted() {
    this.fetchUsers()
  },
  methods: {
    async fetchUsers() {
      this.loading = true
      try {
        const response = await axios.get('/nfc/wechat/users', {
          params: {
            page: this.pagination.page,
            limit: this.pagination.limit,
            subscribe_status: this.filters.subscribe_status,
            keyword: this.filters.keyword
          }
        })
        this.users = response.data.data.data
        this.pagination.total = response.data.data.total
      } catch (error) {
        this.$message.error('获取用户列表失败')
      } finally {
        this.loading = false
      }
    },
    
    handlePageChange(page) {
      this.pagination.page = page
      this.fetchUsers()
    },
    
    sendToUser(user) {
      this.messageForm.user_open_id = user.user_open_id
      this.messageForm.type = 'single'
      this.showSendMessage = true
    },
    
    async sendMessage() {
      if (!this.messageForm.content) {
        this.$message.error('请输入消息内容')
        return
      }
      
      this.sending = true
      try {
        const url = this.messageForm.type === 'single' 
          ? '/nfc/wechat/sendMessage' 
          : '/nfc/wechat/batchSend'
          
        const data = this.messageForm.type === 'single' 
          ? {
              user_open_id: this.messageForm.user_open_id,
              content: this.messageForm.content,
              message_type: 1
            }
          : {
              content: this.messageForm.content,
              message_type: 1,
              user_type: 'all'
            }
            
        const response = await axios.post(url, data)

        if (response.data.code === 0) {
          if (this.messageForm.type === 'single') {
            if (response.data.data.send_result) {
              this.$message.success('消息发送成功')
              this.showSendMessage = false
              this.messageForm = { type: 'single', user_open_id: '', content: '' }
              
              this.$emit('messagesSent')
              this.$root.$emit('messageSent')
              if (this.$parent && this.$parent.refreshMessages) {
                this.$parent.refreshMessages()
              }
            } else {
              const errMsg = response.data.message || '消息发送失败';
              const errDetail = response.data.data?.error?.error_message ? `: ${response.data.data.error.error_message}` : '';
              this.$message.error(errMsg + errDetail)
            }
          } else { // 批量
            if (response.data.data.success_count > 0) {
              this.$message.success(`批量发送成功（成功: ${response.data.data.success_count}/${response.data.data.total_count}）`)
              this.showSendMessage = false
              this.messageForm = { type: 'all', user_open_id: '', content: '' }
              
              this.$emit('messagesSent')
              this.$root.$emit('messageSent')
              if (this.$parent && this.$parent.refreshMessages) {
                this.$parent.refreshMessages()
              }
            } else {
              this.$message.error(`批量发送失败（成功: 0/${response.data.data.total_count}）`)
            }
          }
        } else {
          // 通用错误
          this.$message.error(response.data.message || '发送失败')
        }
      } catch (error) {
        this.$message.error('消息发送失败: ' + (error.response?.data?.message || error.message))
      } finally {
        this.sending = false
      }
    },
    
    // 复制OpenID
    copyOpenId(openId) {
      // 创建临时textarea元素
      const textarea = document.createElement('textarea')
      textarea.value = openId
      document.body.appendChild(textarea)
      textarea.select()
      document.execCommand('copy')
      document.body.removeChild(textarea)
      
      this.$message.success('OpenID已复制到剪贴板')
    }
  }
}
</script>

<style scoped>
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filters {
  margin-bottom: 20px;
}

.filters > * {
  margin-right: 10px;
}
</style>